//
//  WBVideoListViewController.m
//  AVPlayerDemo
//
//  Created by HN on 2021/6/30.
//

#import "WBVideoListViewController.h"

#import "WBVideoListCell.h"

@interface WBVideoListViewController () <UITableViewDelegate, UITableViewDataSource, WBVideoListCellDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property(copy, nonatomic) NSArray *dataArray;

// 记录偏移值,用于判断上滑还是下滑
@property(nonatomic, assign) CGFloat lastScrollViewContentOffsetY;
@property (nonatomic,strong) WBVideoListCell *playingCell;
@end

@implementation WBVideoListViewController

#pragma mark - life
- (void)viewDidLoad {
    [super viewDidLoad];
    [self creatData];
    [self setUI];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self filterShouldPlayCellWithScrollDirection:NO];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [self resetPlayCell];
}

#pragma mark - UI
- (void)setUI {
    self.tableView.tableFooterView = [UIView new];
    self.tableView.tableHeaderView = [UIView new];

    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass(WBVideoListCell.class) bundle:nil] forCellReuseIdentifier:NSStringFromClass(WBVideoListCell.class)];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass(WBVideoListCell.class) bundle:nil] forCellReuseIdentifier:@"player list cell"];
}

#pragma mark - other
- (void)resetPlayCell {
    if (self.playingCell) {
        self.playingCell.model.playTime = self.playingCell.player.currentTime;
        [self.playingCell.player stop];
        self.playingCell.player = nil;
        self.playingCell = nil;
    }
}

- (void)creatData {
    self.dataArray = self.urlsArray;
    
    // 进入播放
    [self resetPlayCell];
    [self filterShouldPlayCellWithScrollDirection:NO];
}

#pragma mark - VideoListCellDelegate
- (void)playButtonClick:(UIButton *)sender {
    NSInteger row = sender.tag - 788;
    if (row != self.playingCell.indexPath.row) {
        [self stopCurrentPlayingCell];
        [self playVideoWithShouldToPlayWithIndexPath:[NSIndexPath indexPathForRow:row inSection:0]];
    }
}

#pragma mark - UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    VideoInfo *model = self.dataArray[indexPath.row];
    
    WBVideoListCell *cell;
    if (model.type == VideoInfoTypeVideo) {
        cell = [tableView dequeueReusableCellWithIdentifier:@"player list cell"];
    } else {
        cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass(WBVideoListCell.class)];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.delegate = self;
    cell.indexPath = indexPath;
    cell.model = model;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 300;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    //判断滚动方向
    BOOL isScrollDownward = NO;
    if (scrollView.contentOffset.y > self.lastScrollViewContentOffsetY) { // Yes-往下滑
        isScrollDownward = YES;
    } else { // NO-往上滑
        isScrollDownward = NO;
    }
    self.lastScrollViewContentOffsetY = scrollView.contentOffset.y;
    
    //停止当前播放的
    [self stopCurrentPlayingCell];
    
    //找出适合播放的并播放
    [self filterShouldPlayCellWithScrollDirection:isScrollDownward];
}

#pragma mark - 播放暂停
- (void)filterShouldPlayCellWithScrollDirection:(BOOL)isScrollDownward {
    if (self.dataArray.count == 0) {
        return;
    }
    //顶部
    if (self.tableView.contentOffset.y <= 0) {
        VideoInfo *model = self.dataArray[0];
        if (model.type == VideoInfoTypeVideo) {
            //其他的已经暂停播放
            if (self.playingCell == nil) {
                [self playVideoWithShouldToPlayWithIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
            } else {
                //第一个正在播放
                if ([self compareToIndexPath1:self.playingCell.indexPath indexPath2:[NSIndexPath indexPathForRow:0 inSection:0]]) {
                    return;
                }
                //其他的没有暂停播放,先暂停其他的再播放第一个
                [self stopVideoWithShouldToStopWithIndexPath:self.playingCell.indexPath];
                [self playVideoWithShouldToPlayWithIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
            }
            return;
        }
    }
    
    //底部
//    if (self.tableView.contentOffset.y + self.tableView.frame.size.height >= self.tableView.contentSize.height) {
//        //其他的已经暂停播放
//        if (self.playingCell == nil) {
//            [self playVideoWithShouldToPlayWithIndexPath:[NSIndexPath indexPathForRow:self.dynamicDatas.count - 1 inSection:0]];
//        } else {
//            //最后一个正在播放
//            if ([self compareToIndexPath1:self.playingCell.indexPath indexPath2:[NSIndexPath indexPathForRow:self.dynamicDatas.count - 1 inSection:0]]) {
//                return;
//            }
//            //其他的没有暂停播放,先暂停其他的再播放最后一个
//            [self stopVideoWithShouldToStopWithIndexPath:self.playingCell.indexPath];
//            [self playVideoWithShouldToPlayWithIndexPath:[NSIndexPath indexPathForRow:self.dynamicDatas.count - 1 inSection:0]];
//        }
//        return;
//    }
    
    //中部(找出可见cell中最合适的一个进行播放)
    NSArray *cellsArray = [self.tableView visibleCells];
    NSArray *newArray = nil;
    if (!isScrollDownward) {
        newArray = [cellsArray reverseObjectEnumerator].allObjects;
    } else {
        newArray = cellsArray;
    }
    [newArray enumerateObjectsUsingBlock:^(WBVideoListCell *cell, NSUInteger idx, BOOL *_Nonnull stop) {
        if (![cell.reuseIdentifier isEqualToString:@"player list cell"]) return;
        
        CGRect rect = [cell.contentBgView convertRect:cell.contentBgView.bounds toView:self.view];
        CGFloat topSpacing = rect.origin.y;
        CGFloat bottomSpacing = self.tableView.frame.size.height - rect.origin.y - rect.size.height;
        if (topSpacing >= -rect.size.height / 3. && bottomSpacing >= -rect.size.height / 3.) {
            if ([self compareToIndexPath1:self.playingCell.indexPath indexPath2:cell.indexPath] == NO) {
                [cell shouldToPlay];
                self.playingCell = cell;
            }
            *stop = YES;
        }
    }];
}

- (BOOL)compareToIndexPath1:(NSIndexPath *)indexPath1 indexPath2:(NSIndexPath *)indexPath2 {
    if ((indexPath1.section == indexPath2.section) && (indexPath1.row == indexPath2.row)) {
        return YES;
    }
    return NO;
}

- (void)stopCurrentPlayingCell {
    //避免第一次播放的时候被暂停
    if (self.tableView.contentOffset.y <= 0) {
        return;
    }
    
    if (self.playingCell != nil) {
        WBVideoListCell *cell = self.playingCell;
        if (![cell.reuseIdentifier isEqualToString:@"player list cell"]) return;
        
        CGRect rect = [cell.contentBgView convertRect:cell.contentBgView.bounds toView:self.view];
        CGFloat topSpacing = rect.origin.y;
        CGFloat bottomSpacing = self.tableView.frame.size.height - rect.origin.y - rect.size.height;
        //当视频播放部分移除可见区域1/3的时候暂停
        if (topSpacing <= -rect.size.height / 3. || bottomSpacing <= -rect.size.height / 3.) {
            cell.model.playTime = cell.player.currentTime;
            [cell.player stop];
            cell.player = nil;
            self.playingCell = nil;
        }
    }
}

- (void)playVideoWithShouldToPlayWithIndexPath:(NSIndexPath *)indexPath {
    WBVideoListCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    if (cell.player) {
        [cell shouldToPlay];
        self.playingCell = cell;
    }
}

- (void)stopVideoWithShouldToStopWithIndexPath:(NSIndexPath *)indexPath {
    WBVideoListCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    if (cell.player && cell.player.isPlaying) {
        cell.model.playTime = cell.player.currentTime;
        [cell.player stop];
        cell.player = nil;
    }
    self.playingCell = nil;
}

@end
